package com.yc.thread;

public class TestThreadLocal implements Runnable {
	Bank bank;
	public TestThreadLocal(Bank b) {
		bank = b;
	}
	
	@Override
	public void run() {
		for (int i = 0; i < 10; i++) {
			bank.set();
		}
		System.out.println(Thread.currentThread() + ":  " + bank.get());
	}
	
	public static void main(String[] args) {
		Bank b = new Bank();
		
		TestThreadLocal tl1 = new TestThreadLocal(b);
		Thread t1 = new Thread(tl1);
		t1.start();
		
		TestThreadLocal tl2 = new TestThreadLocal(b);
		Thread t2 = new Thread(tl1);
		t2.start();
		
		try {
			t1.join();
			t2.join();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		System.out.println(b.get());
		
	}

}

class Bank {
	ThreadLocal<Integer> account = new ThreadLocal<Integer> () {

		@Override
		protected Integer initialValue() {
			return 100;
		}
		
	};
	
	public Integer get() {
		try {
			Thread.sleep(100);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return account.get();
	}
	
	public void set() {
		try {
			Thread.sleep(500);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		account.set(account.get() + 10);
	}
}
